package com.androidservice.dao;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.androidservice.bean.Commodity;

@Repository
public class CommodityDao extends AbstractDao<Commodity>{

	protected CommodityDao() {
		super(Commodity.class);
	}
	
	@SuppressWarnings("unchecked")
	public List<Commodity> findCommoditysByCid(int cid){
		Query query = entityManager.createQuery("select c from Commodity c where c.compang.cid =?1");
		query.setParameter(1, cid);		
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Commodity> findAllCommoditys(){
		Query query = entityManager.createQuery("select c from Commodity c");
		
		return query.getResultList();
	}
	
	public void DeleteCommodityByYid(int yid){
		Query query = entityManager.createQuery("delete from Commodity c where c.yid = ?1");
		query.setParameter(1, yid);
		
		query.executeUpdate();
	}
	
	public void DeleteCommodityByCid(int cid){
		Query query = entityManager.createQuery("delete from Commodity c where c.compang.cid = ?1");
		query.setParameter(1, cid);
		
		query.executeUpdate();
	}

	public Commodity findCommodityByCidAndYid(int cid ,int yid){
		Query query = entityManager.createQuery("select c from Commodity c where c.compang.cid =?1 and c.yid = ?2");
		query.setParameter(1, cid);	
		query.setParameter(2, yid);
		return (Commodity)query.getSingleResult();
	}
	
	public Commodity findCommodityByYid(int yid){
		Query query = entityManager.createQuery("select c from Commodity c where c.yid = ?1");
		query.setParameter(1, yid);
		return (Commodity)query.getSingleResult();
	}
	
	public void saveCommodity(Commodity commodity){
		entityManager.merge(commodity);
	}
	
	public void saveNewCommodity(Commodity commodity){
		entityManager.persist(commodity);
	}
	
}
